import { nextTick } from 'vue'

interface CollapseOptions {
  target: HTMLElement
  isExpanded: boolean
  startHeight?: number
  duration?: number
}

export default class Collapse {
  private target: HTMLElement
  private isExpanded: boolean
  private startHeight: number
  private duration: number

  constructor({ target, isExpanded, duration = 300, startHeight = 0 }: CollapseOptions) {
    this.target = target
    this.isExpanded = isExpanded
    this.startHeight = startHeight
    this.duration = duration
    this.target.style.transition = `max-height ${this.duration}ms ease`
  }

  // 展开
  public expand() {
    this.isExpanded = true
    this.target.style.maxHeight = `${this.startHeight}px`
    requestAnimationFrame(() => {
      this.target.style.maxHeight = `${this.target.scrollHeight}px`
    })
  }

  // 折叠
  public collapse() {
    this.isExpanded = false
    this.target.style.maxHeight = `${this.target.scrollHeight}px`
    requestAnimationFrame(() => {
      this.target.style.maxHeight = `${this.startHeight}px`
    })
  }

  // 更新尺寸
  public async updateSize() {
    if (this.isExpanded) {
      await nextTick()
      this.target.style.maxHeight = `${this.target.scrollHeight}px`
    }
  }

  // 切换
  public toggle() {
    if (this.isExpanded) this.collapse()
    else this.expand()
  }
}
